/**
 * Copyright 2018-2020 stylefeng & fengshuonan (https://gitee.com/stylefeng)
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.stylefeng.guns.core.interceptor;

import cn.stylefeng.guns.core.common.annotion.Authorize;
import cn.stylefeng.guns.core.common.constant.JwtConstants;
import cn.stylefeng.guns.core.common.constant.state.CommonStatus;
import cn.stylefeng.guns.core.common.constant.state.ManagerStatus;
import cn.stylefeng.guns.core.common.entity.ApiResponse;
import cn.stylefeng.guns.core.common.exception.ApiExceptionEnum;
import cn.stylefeng.guns.core.common.exception.BizExceptionEnum;
import cn.stylefeng.guns.core.util.JwtTokenUtil;
import cn.stylefeng.guns.modular.system.entity.User;
import cn.stylefeng.guns.modular.system.service.UserService;
import cn.stylefeng.roses.core.util.RenderUtil;
import io.jsonwebtoken.JwtException;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;


/**
 * Rest Api接口鉴权
 *
 * @author stylefeng
 * @Date 2018/7/20 23:11
 */
public class RestApiInteceptor extends HandlerInterceptorAdapter {

    @Autowired
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof org.springframework.web.servlet.resource.ResourceHttpRequestHandler) {
            return true;
        }
        return check(request, response,handler);
    }

    private boolean check(HttpServletRequest request, HttpServletResponse response,Object handler) {
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        //如果没有Authorize注解，直接跳过，否则去验证token
        if (!method.isAnnotationPresent(Authorize.class)) {
            return true;
        }

        final String authToken = request.getHeader(JwtConstants.AUTH_HEADER);
        if (StringUtils.isNotBlank(authToken)) {
            //验证token是否过期,包含了验证jwt是否正确
            try {
                boolean flag = JwtTokenUtil.isTokenExpired(authToken);
                if (flag) {
                    RenderUtil.renderJson(response, ApiResponse.error(ApiExceptionEnum.TOKEN_EXPIRED));
                    return false;
                }else{
                    //从token中获取userId
                    String userId = JwtTokenUtil.getUsernameFromToken(authToken);
                    request.setAttribute("userId",userId);
                    //判断用户状态
                    User user = userService.getById(userId);
                    if(user==null || ManagerStatus.DELETED.getCode().equals(user.getStatus())){
                        //用户不存在
                        RenderUtil.renderJson(response, ApiResponse.error(ApiExceptionEnum.USER_NOT_EXIT));
                        return false;
                    }
                    if(ManagerStatus.FREEZED.getCode().equals(user.getStatus())){
                        //用户被禁用
                        RenderUtil.renderJson(response, ApiResponse.error(ApiExceptionEnum.USER_DISABLE));
                        return false;
                    }
                }
            } catch (JwtException e) {
                //有异常就是token解析失败
                RenderUtil.renderJson(response, ApiResponse.error(ApiExceptionEnum.TOKEN_ERROR));
                return false;
            }
        } else {
            //header没有带Bearer字段
            RenderUtil.renderJson(response, ApiResponse.error(ApiExceptionEnum.TOKEN_ERROR));
            return false;
        }
        return true;
    }

}
